package com.cy.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cy.commons.utils.EncryptUtil;
import com.cy.system.annotation.SysLog;
import com.cy.system.config.UserSession;
import com.cy.system.entity.Account;
import com.cy.system.entity.Menu;
import com.cy.system.entity.User;
import com.cy.system.entity.UserRole;
import com.cy.system.mapper.AccountMapper;
import com.cy.system.mapper.MenuMapper;
import com.cy.system.mapper.RoleMapper;
import com.cy.system.mapper.UserMapper;
import com.cy.system.service.AccountService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Service
public class AccountServiceImpl implements AccountService {
	private final static Logger logger = Logger.getLogger(AccountServiceImpl.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
	public static int SALT_SIZE=8;
	public static int HASH_ITERATIONS=1024;
	
	@Resource
	AccountMapper accountMapper;
	@Resource
	UserMapper userMapper;
	@Resource
	MenuMapper menuMapper;
	@Resource
	RoleMapper roleMapper;
	
	@Override
	@SysLog(operType="添加账号",isWrite=false)
	public int addAccount(Account account,HttpSession session) {
		logger.info("==> "+account);
		logger.info("==> password["+account.getPassword()+"]");
		String password = account.getPassword();
		account.setPassword(this.EncryptPassword(password));
		account.setUpdateBy("self");
		account.setUpdateDate(new Date());
		int resInt = accountMapper.addAccount(account);
		logger.info("==> 账号写入 accountId["+account.getAccountId()+"]");
		User user = new User();
		user.setUserName(account.getLoginName());
		user.setAccountId(account.getAccountId());
		User userSession = (User) session.getAttribute("userSession");
		user.setUpdateBy(userSession.getUserName());
		user.setUpdateDate(sdf.format(new Date()));
		resInt = userMapper.addUser(user);
		logger.info("==> 用户写入 userId["+user.getUserId()+"]");
		List<UserRole> list = new ArrayList<UserRole>(); 
		UserRole userRole = new UserRole();
		userRole.setRoleId(7);
		userRole.setUserId(user.getUserId());
		list.add(userRole);
		userMapper.setUserRoleIds(list);
		return resInt;
	}

	@Override
	public int deleteAccount(int id) {
		return accountMapper.deleteAccountById(id);
		
	}

	@Override
	@SysLog(operType="更新账号")
	public HashMap<String,Object> updateAccount(String oldPassword,String newPassword,int accountId) {
		HashMap<String,Object> res = new HashMap<String,Object>();
		if(this.vaildatePassword(oldPassword, 
				accountMapper.getPasswordById(accountId)
				)
			) {
			String password = newPassword;
			Account account = new Account();
			account.setPassword(this.EncryptPassword(password));
			account.setUpdateBy("root");
			account.setUpdateDate(new Date());
			accountMapper.updateAccount(account);
			res.put("result", "更新成功");
		}else {
			res.put("result","更新失败");
		}
		return res;
	}

	@Override
	@SysLog(operType="查询账号")
	public Account getAccountById(int accountId) {
		
		return accountMapper.getAccountById(accountId);
	}

	@Override
	public List<Account> getAllAccountList(Page page) {
		PageHelper.startPage(page.getPageNum(),page.getPageSize());
		List<Account> resList = accountMapper.getAllAccountList();
		logger.info("==> 分页查询结果size["+resList.size()+"]");
		return resList;
	}

	@Override
	@SysLog(operType="验证密码")
	public Boolean vaildatePassword(String targetPassword, String sourcePassword) {
		System.out.println(sourcePassword);
		String saltHex = sourcePassword.substring(0, SALT_SIZE*2);
		byte[] salt = EncryptUtil.decodeHex(saltHex);
		byte[] sha1Password = EncryptUtil.sha1(targetPassword.getBytes(), salt, HASH_ITERATIONS);
		String EncryptTargetPassword = EncryptUtil.encodeHex(salt)+EncryptUtil.encodeHex(sha1Password);
		return EncryptTargetPassword.equals(sourcePassword);
	}

	@Override
	@SysLog(operType="密码加密")
	public String EncryptPassword(String password) {
		//生成一个随机数 ，所谓的salt 盐 ，随机字节数组
		byte[] salt = EncryptUtil.generateSalt(SALT_SIZE);
		//盐+密码   进行sha1的加密
		byte[] sha1Password = EncryptUtil.sha1(password.getBytes(), salt, HASH_ITERATIONS);
		//盐可逆加密+(盐+密码 sha1加密后)可逆加密
		return EncryptUtil.encodeHex(salt)+EncryptUtil.encodeHex(sha1Password);
	}

	@Override
	public String getPasswordById(int accountId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@SysLog(operType="登录系统")
	public User toLogin(Account account,HttpSession session) {
		System.out.println("toLogin");
		UserSession userSession = new UserSession();
		Account dataAccount= accountMapper.getAccountByLoginName(account.getLoginName());
		if(null!=dataAccount) {
			if(this.vaildatePassword(account.getPassword(),dataAccount.getPassword())
					) {
					session.setAttribute("userSession", userMapper.getUserByAccountId(dataAccount.getAccountId()));
					userSession.setUserSession(session);
					System.out.println(session.getAttribute("userSession"));
					return userMapper.getUserByAccountId(dataAccount.getAccountId());
				}
		}
		
		return null;
	}

	@Override
	@SysLog(operType="初始化权限菜单")
	public List<Menu> initMenu(User user) {
		List<Menu> resMenuList = new ArrayList<Menu>();
		List<Menu> allMenu = menuMapper.getAllMenu();
		/*User userSession = (User) session.getAttribute("userSession");*/
		List<Integer> roleIds = userMapper.getUserRoleIds(user.getUserId());
		/*List<Integer> roleIds = userMapper.getUserRoleIds(userId);*/
		List<Integer> menuIds = new ArrayList<Integer>();
		for(int roleId : roleIds) {
			menuIds.addAll(roleMapper.getMenuIdsByRoleId(roleId)) ;
		}
		HashSet menuIdsSet = new HashSet(menuIds);
		menuIds.clear();
		menuIds.addAll(menuIdsSet);
		for(Menu menu : allMenu) {
			if(menuIds.contains(menu.getMenuId())) {
				resMenuList.add(menu);
			}		
		}
		return resMenuList;
	}

	@Override
	public Account getAccountByLoginName(String loginName) {
		
		return accountMapper.getAccountByLoginName(loginName);
	}
	
	

	

}
